# Copyright (c) 2007 Fabio Makoto Akita
# 
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
# 
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

# Author: AkitaOnRails (www.akitaonrails.com)
# Support: Surgeworks LLC (www.surgeworks.com)

#
# WARNING: DO NOT EDIT THIS FILE MANUALLY - IT IS AUTOMATICALLY GENERATED BY THE PLUGIN
#
module SyncsHelper
  # This process has 3 major steps, this is the first: the handshake operation
  # is comprised of 2 main steps: requesting a challenge from the server, and
  # sending back the response. Upon authentication, the server sends back the
  # most recent timestamp from the last successful syncing
  module Handshake    
    # client-side call to login for the first time
    # returns the new user and the latest svn revision
    def bootstrap_login(options = {})
      create_user = options[:create_user].nil? ? true : options[:create_user]
      
      # try to first authenticate with the server
      req = http_open_post(address, $SYNC_CONFIG[:handshake_uri]) do |request|
        request.set_form_data({ 'username' => options[:username], 'password' => options[:password]})
      end
      case req
      when Net::HTTPSuccess
        @user = User.new
        result = YAML.load(expand(req.body))
        user_tmp = result[:user]
        last_replica = result[:last_replica]
        # create the new user
        user_tmp.attributes.each { |k, v| @user.send("#{k}=".to_sym, v) if @user.respond_to?("#{k}=".to_sym) } 
        @user.password = options[:password]
        @user.password_confirmation = options[:password]
        # update the current Replica index
        SyncSetting.load.update_attributes(:last_synced => last_replica)
        begin
          @user.save! if create_user
          RAILS_DEFAULT_LOGGER.debug "Successful first login. Last Replica: #{last_replica}. User: #{@user.to_yaml}"
          return [@user, last_replica]
        rescue => e
          RAILS_DEFAULT_LOGGER.debug "Error saving user from first login: #{e.inspect}"
          raise e
        end
      end
    end
    
    # the server answers to a 2-way handshake process
    # the GET answers with a challenge-response token
    # the POST compares the received response
    #  if OK, sends back last synced time record in the server
    def handshake
      if request.get?
        session[:challenge] = UUID.timestamp_create.to_s
        render :text => compress(session[:challenge]), :status => 200
      else
        # this is first login procedure
        if params[:username] 
          @user = User.authenticate(params[:username], params[:password])
          if @user
            result = {
              :user          => @user,
              :last_replica  => Replica.find(:first, :select => "max(id) as max_id").max_id
            }
            render :text => compress(result.to_yaml)
          else
            render :text => compress("Incorrect Username/password"), :status => 403
          end
        else
          # for the server to compare the response, the client has to send back
          # the http cookie for the server to retrieve the original challenge
          if handshake_response(session[:challenge], params[:client_id], false) == params[:challenge_response]
            session[:client_id] = params[:client_id]
            # the user is authenticated as a RemoteClient, now has to associate with the
            # machine id sent. If it doesn't exist, create a new pairing. This means the
            # Replica table in the other side is also brand new, starting from ID 1 and
            # we will retrieve everything back from the server
            session[:remote_client] = current_remote_client
            session[:machine]       = current_remote_client.remote_machines.find_by_machine_id(params[:machine_id])
            session[:machine] ||= RemoteMachine.create :machine_id => params[:machine_id],
              :remote_client => current_remote_client
            token = session[:machine].last_synced || -1
            
            payload = Replica.down(params[:start_id], session[:machine].machine_id, :count => true)
            result = {
                :last_synced          => token, 
                :server_machine_id    => SyncSetting.load.unique_machine_id,
                :downloadable_items   => payload.total ,
                :version              => Replica.version 
              }
            handshake_hook(result) if respond_to? :handshake_hook, true
            render :text => compress(result.to_yaml), 
              :status               => 200, 
              :content_type         => 'application/x-yaml'
          else
            session[:client_id] = nil
            render :text => compress("Incorrect Challenge-Response"), :status => 403
          end
        end
      end
    end

    private
    
    # before_filter for synchronization
    # Expects to have session[:user] populated with the remote client user id.
    # This is already configured in the SyncsController class
    def authenticated?
      # if this is the client, check :user, if this is the server, check :client_id
      if session[:user].nil? and session[:client_id].nil?
        render :text => "User not logged in", :status => 403
        return false
      else
        return true
      end
    end
  
    # Executes a remote handshake with challenge-response authentication
    # this is to be called from the client's end, in the perform_sync action
    #
    # - Client requests a challenge
    # - Client uses the challenge with its internal guid and generates a SHA1 response
    # - Client sends the response back
    # - Client receives back the last successful synced time from the server
    #
    # Can be configured in the syncable.yml under :handshake_uri
    def handshake_authenticate(address)
      # request the challenge
      req = http_open_get(address, $SYNC_CONFIG[:handshake_uri])
      case req
      when Net::HTTPSuccess
        # generate response and send back with user_id
        resp = handshake_response(expand(req.body), current_client.id)
        req = http_open_post(address, $SYNC_CONFIG[:handshake_uri]) do |request|
          request.set_form_data({
            'client_id'          => current_client.id, 
            'challenge_response' => resp, 
            'start_id'           => current_client.last_synced || -1,
            'machine_id'         => $SYNC_CONFIG[:unique_machine_id] })
        end
        case req
        when Net::HTTPSuccess
          return YAML.load(expand(req.body))
        end
      end    
      nil
    end
  
    # Helper for both the client and server to calculate
    # the response digest from the challenge key
    def handshake_response(challenge, client_id, client = true)
      if client
        u = User.find(client_id)
      else
        u = RemoteClient.find_by_client_id(client_id)
      end
      Digest::SHA1.hexdigest("#{challenge}-#{client_id}-#{u.guid}")
    end    
  end
end